﻿using Rhino;
using Rhino.Commands;
using Rhino.DocObjects;
using Rhino.Geometry;
using Rhino.Input;
using Rhino.Input.Custom;
using System;
using System.Collections.Generic;
using System.Linq;

namespace YangTools.Realization
{
    class AutoAreaRectangle
    {
        /// <summary>
        /// 添加一个矩形，并在矩形中心添加自动显示面积的文字物件
        /// </summary>
        public void Add()
        {
            // 添加一个矩形
            Point3d center;
            var id = AddRectangle(out center);
            if (id == Guid.Empty) return;

            // 获取前缀
            var preText = RhinoHelper.UserInterface.GetString("请输入面积文字的前缀文字：");

            // 获取单位后缀
            string uStr = "";
            if (RhinoDoc.ActiveDoc.ModelUnitSystem == UnitSystem.Meters) uStr = "㎡";
            if (RhinoDoc.ActiveDoc.ModelUnitSystem == UnitSystem.Millimeters) uStr = "mm²";

            // 添加文字物体
            var t = $"{preText}%<Area(\"{id}\")>%{uStr}";
            var f = RhinoDoc.ActiveDoc.DimStyles.Current;
            var p = new Plane(RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.ConstructionPlane()) { Origin = center };
            RhinoHelper.Geometry.AddTextEntity(t, p, f.TextHeight, f.Font, false, false, TextJustification.MiddleCenter);

            Rhino.RhinoDoc.ActiveDoc.Views.Redraw();
        }
        /// <summary>
        /// 获取一个矩形，并进行动态绘制矩形和面积
        /// </summary>
        /// <param name="center"></param>
        /// <returns></returns>
        private Guid AddRectangle(out Point3d center)
        {
            center = RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.ConstructionPlane().Origin;
            var point1 = RhinoHelper.UserInterface.GetPoint("请选择矩形的第一个角点：");
            if(point1.Count==0) return Guid.Empty;

            void AddRectangle_DynamicDraw(object sender, GetPointDrawEventArgs e)
            {
                var startPoint = point1[0];
                var endPoint = e.CurrentPoint;

                // 绘制矩形
                var a = new Rectangle3d(e.Viewport.ConstructionPlane(), startPoint, endPoint);
                e.Display.DrawPolyline(a.ToPolyline(), System.Drawing.Color.Black);

                // 在矩形中心绘制 面积文字
                var centerPoint = (startPoint + endPoint) / 2;
                var centerPlane = e.Viewport.ConstructionPlane();
                centerPlane.Origin = centerPoint;

                var f = RhinoDoc.ActiveDoc.DimStyles.Current;

                var area = Convert.ToInt32(Math.Abs((startPoint.X - endPoint.X) * (startPoint.Y - endPoint.Y)));
                // 这里的 TextHeight 不知道为什么和添加的TextEntity不一样，所以通过除以7保持一致
                e.Display.Draw3dText(area.ToString(), System.Drawing.Color.Black, centerPlane, f.TextHeight/7, f.Font.FaceName, false, false, TextHorizontalAlignment.Center, TextVerticalAlignment.Middle);
            }
            var point2 = RhinoHelper.UserInterface.GetPoint("请选择矩形的第二个角点：", AddRectangle_DynamicDraw);
            if (point2.Count == 0) return Guid.Empty;

            var rec = new Rectangle3d(RhinoDoc.ActiveDoc.Views.ActiveView.ActiveViewport.ConstructionPlane(), point1[0], point2[0]);
            center = rec.Center;
            return RhinoDoc.ActiveDoc.Objects.AddPolyline(rec.ToPolyline());
        }

        
        internal void Reassociate()
        {
            // 选择文字物件
            GetObjectGeometryFilter customFilter = (RhinoObject rhObject, GeometryBase geometry, ComponentIndex componentIndex) => (geometry as TextEntity) != null;
            var textObjects = RhinoHelper.Selection.GetObjects("选择要链接的文字物件：", ObjectType.AnyObject, 1, 0, true, false, customFilter);
            if (textObjects.Count == 0) return;

            // 选择封闭曲线
            GetObjectGeometryFilter customFilter2 = (RhinoObject rhObject, GeometryBase geometry, ComponentIndex componentIndex) => (geometry as Curve).IsClosed;
            var closedCrve = RhinoHelper.Selection.GetObjects("选择要链接的封闭曲线：", ObjectType.Curve, 1, -1, true, false, customFilter2); // 只能选择一个
            if (closedCrve.Count == 0) return;
            var newId = closedCrve[0].Id;

            // 修改文字内容
            foreach (var text in textObjects)
            {
                var t = (text as TextObject).TextGeometry;
                string oldText = t.RichText;

                //var oldText = $"%<Area(\"{Guid.NewGuid()}\")>%";
                var s = oldText.IndexOf("%<Area(\"");
                string newText;
                if (s != -1)
                {
                    // 如果文字物体原本就显示了一个图形的面积，就替换这个图形
                    var source = oldText.Substring(s + 8, 36);
                    newText = oldText.Replace(source, newId.ToString());
                }
                else
                {
                    // 否则就在原始文字的后面添加面积显示
                    newText = oldText + $"%<Area(\"{newId}\")>%";
                }

                t.RichText = newText;
                RhinoDoc.ActiveDoc.Objects.Replace(text.Id, t);
                RhinoDoc.ActiveDoc.Views.Redraw();
            }
        }

    }
}
